package server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;

import service.impl.EventImpl;
import service.impl.HouseImpl;
import service.impl.ProductImpl;
import service.impl.UserImpl;
import service.impl.UserPropertyImpl;

/**
 * Created by Administrator on 2016/12/15.
 */
public class LocalServer {

    private int port;

    public LocalServer(int port){
        this.port=port;
    }

    public void start() throws IOException {
        ServerSocket serverSocket=new ServerSocket(port);
        System.out.println("Start : "+port);
        while(true){
            Socket socket=serverSocket.accept();
            ServerThread serverThread=new ServerThread(socket);
            serverThread.start();
        }
    }

    class ServerThread extends Thread{

        private Socket socket;
        private InputStream inputStream;
        private String method;
        private String urlPath;
        private OutputStream outputStream;

        public ServerThread(Socket socket) {
            this.socket = socket;
        }
        
        public void run(){
            try {
                this.inputStream=socket.getInputStream();
                DataInputStream dataInputStream=new DataInputStream(inputStream);
                String rs=dataInputStream.readLine();
                this.method=rs.substring(0,4).trim();
                System.out.println("---------"+this.method);
                this.urlPath=rs.split(" ")[1];
                socket.setSoTimeout(50);
                System.out.println("客户端socket请求数据流："+rs);
                outputStream=socket.getOutputStream();
                if("get".equalsIgnoreCase(this.method)){
                    doGet(outputStream);
                }else if("post".equalsIgnoreCase(this.method)){
                    doPost(dataInputStream,outputStream,rs);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private void doGet(OutputStream outputStream) throws IOException {
            String queryresource=getQueryResource(urlPath);
            String head=getHead(queryresource);
            byte[] data=null;
            byte[] bytes=new byte[1024];
            int readNum;
            while(true){
                try{
                    readNum=inputStream.read(bytes);
                    if(readNum<0)
                        break;
                }catch (InterruptedIOException e){
                    data=getFileByte("webapp"+queryresource);
                }
                if(data!=null){
                    try{
                        outputStream.write(head.getBytes("utf8"));
                        outputStream.write(data);
                        outputStream.close();
                    }catch (Exception e){
                        e.getMessage();
                    }
                    break;
                }
            }
        }

        private void doPost(DataInputStream dataInputStream,OutputStream outputStream,String rs) throws Exception {
            int contentLength=0;
            String rsString=dataInputStream.readLine();
            while(rsString!=null){
                rsString=dataInputStream.readLine();
                if(rsString.equals("")){
                    break;
                }else if(rsString.indexOf("Content-Length")!=-1){
                    contentLength=Integer.parseInt(rsString.substring(rsString.indexOf("Content-Length")+16));
                }
            }
            int bufsize=0;
            if(contentLength!=0){
                byte[] buf=new byte[contentLength];
                while (bufsize<contentLength){
                    int a=dataInputStream.read();
                    buf[bufsize++]=(byte)a;
                }
                String result= URLDecoder.decode(new String(buf,0,bufsize),"utf8");
                System.out.println("ajax 传值为："+result);
                String str=rs.replaceAll(" ","");
                String flag="";
                for(int i=5;i<str.length();i++){
                    if(str.charAt(i)=='?'){
                        break;
                    }
                    flag+=str.charAt(i);
                }
                ProductImpl product=new ProductImpl();
                HouseImpl house=new HouseImpl();
                UserImpl user=new UserImpl();
                UserPropertyImpl userProperty=new UserPropertyImpl();
                EventImpl event=new EventImpl();
                String queryresource=getQueryResource(urlPath);
                String head=getHead(queryresource);
                System.out.println("-----"+flag);
                switch (flag){  //调用接口
                    case "init":
                        System.out.println(userProperty.userPro(Integer.parseInt(result)));
                        System.out.println(userProperty.userThings(Integer.parseInt(result)));
                        System.out.println(userProperty.userPro(Integer.parseInt(result))+","+userProperty.userThings(Integer.parseInt(result)));
                        outputStream.write(head.getBytes("utf8"));
                        outputStream.write((userProperty.userPro(Integer.parseInt(result))+","+userProperty.userThings(Integer.parseInt(result))).getBytes());
                        break;
                    case "first":
                        int logTimes=1;
                        if(logTimes==1){
                            System.out.println(product.productInit());
                            System.out.println(house.houseInit());
                            System.out.println(product.productInit()+","+house.houseInit());
                            outputStream.write(head.getBytes("utf8"));
                            outputStream.write((product.productInit()+","+house.houseInit()).getBytes());
                        }else{
                            System.out.println(product.productHav(Integer.parseInt(result)));
                            System.out.println(house.houseHav(Integer.parseInt(result)));
                            System.out.println(product.productHav(Integer.parseInt(result))+","+house.houseHav(Integer.parseInt(result)));
                            outputStream.write(head.getBytes("utf8"));
                            outputStream.write((product.productHav(Integer.parseInt(result))+","+house.houseHav(Integer.parseInt(result))).getBytes());
                        }
                        break;
                    case "other":
                        System.out.println(product.productHav(Integer.parseInt(result))+","+house.houseHav(Integer.parseInt(result)));
                        outputStream.write(head.getBytes("utf8"));
                        outputStream.write((product.productHav(Integer.parseInt(result))+","+house.houseHav(Integer.parseInt(result))).getBytes());
                        break;
                    case "event":
                        String back=event.eventBack(result);
                        System.out.println(back);
                        outputStream.write(head.getBytes("utf8"));
                        outputStream.write(back.getBytes());
                        break;
                    case "login":
                        String l=user.loginSub(result)+"";
                    	System.out.println(l);
                    	outputStream.write(head.getBytes("utf8"));
                    	outputStream.write(l.getBytes());
                        break;
                    case "register":
                        String r=user.regSub(result)+"";
                    	System.out.println(r);
                    	outputStream.write(head.getBytes("utf8"));
                    	outputStream.write(r.getBytes());
                        break;
                    case "buyThings":
                    	user.bugThings(result);
                    	break;
                    case "save":
                    	boolean success = user.save(result);
                    	outputStream.write(head.getBytes("utf8"));
                    	if(success){
                    		String s = "保存成功";
                    		outputStream.write(s.getBytes());
                    	}
                    	else{
                    		String s = "保存失败";
                    		outputStream.write(s.getBytes());
                    	}
                    	break;
                    case "rank":
                    	System.out.println(event.getRank());
                    	outputStream.write(head.getBytes("utf8"));
                    	outputStream.write(event.getRank().getBytes());
                    	break;
                }
            }
            dataInputStream.close();
            outputStream.close();
            
        }

        public  byte[] getFileByte(String filename) throws IOException {
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            File file=new File(filename);
            FileInputStream fis=new FileInputStream(file);
            byte[] b=new byte[1000];
            int read;
            while((read=fis.read(b))!=-1){
                baos.write(b,0,read);
            }
            fis.close();
            baos.close();
            return baos.toByteArray();
        }

        private String getHead(String queryresource) {
            String filename="";
            int index=queryresource.lastIndexOf("/");
            filename=queryresource.substring(index+1);
            String[] filetypes=filename.split("\\.");
            String filetype=filetypes[filetypes.length-1];
            if(filetype.equals("html")||filetype.equals("js")){
                return "HTTP/1.0 200OK\n"+"Content-Type:text/html\n" + "Server:myserver\n" + "\n";
            }
            else if(filetype.equals("jpg")||filetype.equals("gif")||filetype.equals("png")){
                return "HTTP/1.0 200OK\n"+"Content-Type:image/jpeg\n" + "Server:myserver\n" + "\n";
            }
            else return "HTTP/1.0 200OK\n"+"Content-Type:text/html\n" + "Server:myserver\n" + "\n";

        }

        private String getQueryResource(String queryurl) {
            String queryresource=null;
            int index=queryurl.indexOf('?');
            if(index!=-1){
                queryresource=queryurl.substring(0,queryurl.indexOf('?'));
            }
            else
                queryresource=queryurl;
            index=queryresource.lastIndexOf("/");
            if(index+1==queryresource.length()){
                queryresource=queryresource+"index.html";
            }
            else{
                String filename=queryresource.substring(index+1);
                if(!filename.contains("."))
                    queryresource=queryresource+".html";
            }
            return queryresource;
        }

    }

}